package org.moon.framework.autoconfigure.rabbitmq.producer;

import org.moon.framework.autoconfigure.rabbitmq.MqttAutoConfiguration;
import org.moon.framework.autoconfigure.rabbitmq.config.MqttConfig;
import org.moon.framework.autoconfigure.rabbitmq.constant.MqttConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.IntegrationComponentScan;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * 消息生产
 * @author ninglong
 * @Date 2020/11/5 18:11
 */
@Configuration
@IntegrationComponentScan
@ConditionalOnProperty(value="moon.mqtt.enabled",havingValue = "true")
@AutoConfigureBefore(MqttAutoConfiguration.class)
public class MqttOutboundConfiguration {

    @Autowired
    private MqttConfig mqttConfig;

    /**
     * MQTT生产端发布通道（消息出站）
     *
     * @return {@link MessageChannel}
     */
    @Bean(name = MqttConstants.CHANNEL_NAME_OUT)
    public MessageChannel outboundChannel() {
        return new DirectChannel();
    }

    /**
     * MQTT生产端发布处理器（消息出站）
     *
     * @param factory {@link MqttPahoClientFactory}
     * @return {@link MessageHandler}
     */
    @Bean
    @ServiceActivator(inputChannel = MqttConstants.CHANNEL_NAME_OUT)
    public MessageHandler outboundHandler(
            @Qualifier(MqttConstants.FACTORY_NAME) MqttPahoClientFactory factory) {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                mqttConfig.getClientId() + "_producer"+System.currentTimeMillis(), factory);
        messageHandler.setAsync(true);
        messageHandler.setDefaultRetained(false);
        messageHandler.setDefaultTopic("test");
        return messageHandler;
    }
}
